//
//  TF_StoyCopyTextView.swift
//  TalkfunSDKDemo
//
//  Created by 邓盛明 on 2021/12/29.
//  Copyright © 2021 Talkfun. All rights reserved.
//

import UIKit

class TF_StoyCopyTextView: UITextView ,UITextViewDelegate{
    var url:String = ""
    var urlArr = NSArray()
    //禁用所有长按文本框操作
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        UIMenuController.shared.isMenuVisible = false
      
        self.resignFirstResponder()
        return false
    }
     
   @objc public func addHyperlink(font:UIFont,attributedText:NSMutableAttributedString)
    {
        //禁止输入
        self.isEditable = false
        self.url = ""
        self.delegate = self
        let msg = attributedText.string as String
        
        if (TalkfunSharedTools.isWhetherNoUrl(msg)) {
            self.url = msg as String

        } else {
            
            self.urlArr = TalkfunSharedTools.getURLFromStr(msg) as NSArray
            if (self.urlArr.count > 0) {
                self.url = self.urlArr[0] as! String;
            }

        }
        if (self.url.count > 4) {
            if (self.urlArr.count > 1) {
                
                for i in stride(from: 0, to: self.urlArr.count ,by: 1) {

                    let url = self.urlArr[i] as! String
            
                    let s = "digitalcer\(i)://"
                 
                    
                    attributedText.attributes(url: url, font: font, color: UIColor(red: 15/255.0, green: 44/255.0, blue: 187/255.0, alpha: 1.0), link: s)
                }

            }
            else {


                let s = "digi11://"
           
                attributedText.attributes(url: self.url, font: font, color: UIColor(red: 15/255.0, green: 44/255.0, blue: 187/255.0, alpha: 1.0), link: s)
            }

        }
    }
    
    @available(iOS 10.0, *)
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        
        
        let scheme:NSString = URL.scheme! as NSString
        var isUrl:Bool = false
        if (self.urlArr.count > 1) {
          
            for i in stride(from: 0, to: self.urlArr.count ,by: 1) {
                let str1 = "digitalcer\(i)"
                if scheme as String == str1 {
                  
                    let url = self.urlArr[i] as! NSString
                    isUrl = true
                    TalkfunSharedTools.openUrl(str: url)
               
                }
            }
        } else {
            if (scheme == "digi11") {
                isUrl = true
                TalkfunSharedTools.openUrl(str: self.url as NSString)
               
            }
           
        }
        
        return isUrl
    }
  
}
